package com.algorithm.code.list;


/**
 * @program: study
 * @className: DoubleList
 * @description: 双向链表
 * @author: kukuxiahuni
 * @create: 2020-01-21 16:29
 * @version: v1.0
 **/
public class DoubleList<T> implements BaseList<T> {

    /**
     * 头结点：不存储任意数据
     */
    private final Node<T> head = new Node<>(null, null, null);

    private Node<T> tail = head;

    public static void main(String[] args) {
        DoubleList<Integer> doubleList = new DoubleList<>();
        System.out.println(doubleList.isEmpty());
        for (int i = 0; i < 10; ++i) {
            doubleList.add(i);
        }
        doubleList.printAll();
        for (int i = 0; i < 9; ++i) {

            doubleList.deleteFirst(i);
        }
        System.out.println("***********************");
        doubleList.printAll();
        System.out.println(doubleList.isEmpty());


    }


    @Override
    public void deleteFirst(T value) {

        if (value == null || isEmpty()) {
            return;
        }

        Node<T> p = head;
        while (p.next != null) {
            Node<T> q = p.next;

            if (q.value.equals(value)) {

                /**
                 * 如果是尾节点
                 */
                if (q == tail) {
                    p.next = null;
                    tail = p;
                } else {
                    p.next = q.next;
                    q.next.pre = p;
                }
                return;
            }
            p = p.next;
        }
    }

    @Override
    public void add(T value) {

        if (value == null) {
            return;
        }
        /**
         * 新建节点
         */
        Node<T> node = new Node<>(value, tail, tail.next);
        tail.next = node;
        tail = node;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public void printAll() {

        Node<T> p = this.head.next;

        while (p != null) {
            System.out.println(p.value);
            p = p.next;
        }


    }

}
